package com.stellar.core.encrypt.handler;

import com.baomidou.mybatisplus.core.toolkit.Constants;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @ClassName：AESEncryptHandler
 * @Description: AES加密算法
 * @Author: Jqcc
 * @Date: 2025/3/13
 */
@Slf4j
public class AESEncryptHandler implements EncryptHandler {

    /**
     * aes算法需要秘钥key
     */
    private String key = "e247d43f717440a1";

    /**
     * aes算法需要一个偏移量
     * AES算法的偏移量长度必须为16字节（128位）
     */
    private String aesIv = "9491a86cb4574440";


    @Override
    public String encrypt(String content) {
        try {
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), Constants.AES);
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, Constants.AES);
            IvParameterSpec iv = new IvParameterSpec(aesIv.getBytes(StandardCharsets.UTF_8));
            Cipher cipher = Cipher.getInstance(Constants.AES_CBC_CIPHER);
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, iv);
            byte[] valueByte = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(valueByte);
        } catch (Exception e) {
            log.error("加密失败：", e);
            throw new RuntimeException("encrypt fail!", e);
        }
    }

    @Override
    public String decrypt(String content) {
        try {
            byte[] originalData = Base64.getDecoder().decode(content.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), Constants.AES);
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, Constants.AES);
            IvParameterSpec iv = new IvParameterSpec(aesIv.getBytes(StandardCharsets.UTF_8));
            Cipher cipher = Cipher.getInstance(Constants.AES_CBC_CIPHER);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
            byte[] valueByte = cipher.doFinal(originalData);
            return new String(valueByte);
        } catch (Exception e) {
            log.error("解密失败：", e);
            throw new RuntimeException("decrypt fail!", e);
        }
    }

    public static void main(String[] args) {
        AESEncryptHandler handler = new AESEncryptHandler();
        System.out.println(handler.encrypt("123456"));
        System.out.println(handler.decrypt(handler.encrypt("123456")));
    }
}
